package com.qianying.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianying.comment.CommonResult;
import com.qianying.entity.PlatformCompany;
import com.qianying.mapper.PlatformCompanyMapper;
import com.qianying.service.PlatformCompanyService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 平台公司Service实现类
 * 实现平台公司的增删改查业务逻辑
 */
@Service
public class PlatformCompanyServiceImpl extends ServiceImpl<PlatformCompanyMapper, PlatformCompany> implements PlatformCompanyService {

    @Override
    public CommonResult<Page<PlatformCompany>> getPage(Page<PlatformCompany> page, String companyName) {
        // 构建查询条件（支持公司名称模糊查询）
        LambdaQueryWrapper<PlatformCompany> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(companyName)) {
            queryWrapper.like(PlatformCompany::getCompanyName, companyName);
        }
        // 执行分页查询
        Page<PlatformCompany> companyPage = baseMapper.selectPage(page, queryWrapper);
        return CommonResult.success(companyPage);
    }

    @Override
    public CommonResult<PlatformCompany> getById(Long id) {
        PlatformCompany company = baseMapper.selectById(id);
        if (company != null) {
            return CommonResult.success(company);
        }
        return CommonResult.failed("未找到ID为" + id + "的平台公司");
    }

    @Override
    public CommonResult<?> saveCompany(PlatformCompany company) {
        // 简单校验：公司名称必填
        if (!StringUtils.hasText(company.getCompanyName())) {
            return CommonResult.failed("公司名称不能为空");
        }
        // 执行新增
        int rows = baseMapper.insert(company);
        return rows > 0 ? CommonResult.success("新增平台公司成功") : CommonResult.failed("新增平台公司失败");
    }

    @Override
    public CommonResult<?> updateCompany(PlatformCompany company) {
        // 校验ID和公司名称
        if (company.getId() == null) {
            return CommonResult.failed("公司ID不能为空");
        }
        if (!StringUtils.hasText(company.getCompanyName())) {
            return CommonResult.failed("公司名称不能为空");
        }
        // 执行更新
        int rows = baseMapper.updateById(company);
        if (rows > 0) {
            return CommonResult.success("更新平台公司成功");
        }
        return CommonResult.failed("更新失败，未找到ID为" + company.getId() + "的平台公司");
    }

    @Override
    public CommonResult<?> removeById(Long id) {
        if (id == null) {
            return CommonResult.failed("公司ID不能为空");
        }
        // 执行删除
        int rows = baseMapper.deleteById(id);
        return rows > 0 ? CommonResult.success("删除平台公司成功") : CommonResult.failed("删除失败，未找到ID为" + id + "的平台公司");
    }
}
